/**
 * 客户端测试2072接口脚本
 * 专注于测试：副将上阵/下阵/位置交换功能
 */

const http = require('http');
const WebSocket = require('ws');

// 测试配置
const CONFIG = {
    server: {
        host: 'localhost',
        port: 3000,
        protocol: 'http'
    },
    testUser: {
        mobile: '17091271111',
        password: '123456',
        passwordHash: 'e10adc3949ba59abbe56e057f20f883e'
    },
    testCharacter: {
        name: '测试角色',
        sex: 1,
        roleType: 1,
        headIndex: 2
    }
};

class Code2072Tester {
    constructor() {
        this.token = null;
        this.userId = null;
        this.ws = null;
        this.characters = [];
        this.selectedCharacter = null;
        this.testResults = [];
        this.deputyList = [];
        this.operationResults = [];
    }

    async runTest() {
        console.log('⚔️ 开始客户端2072接口测试...\n');
        console.log('测试目标：HTTP登录 → WebSocket连接 → 选择角色 → 查询副将列表 → 测试副将操作功能\n');

        try {
            await this.testHttpLogin();
            await this.testWebSocketConnection();
            await this.testQueryCharacters();

            if (this.characters.length === 0) {
                await this.testCreateCharacter();
                await this.testQueryCharacters();
            }

            await this.testSelectCharacter();
            await this.testQueryDeputyList('初始状态');
            await this.testCode2072DeployDeputy();
            await this.testQueryDeputyList('上阵后');
            await this.testCode2072RemoveDeputy();
            await this.testQueryDeputyList('下阵后');
            await this.testCode2072SwapPosition();
            await this.testQueryDeputyList('位置交换后');
            await this.testCode2072MultipleOperations();
            await this.testQueryDeputyList('多次操作后');
            await this.validateOperationResults();
            await this.testDisconnect();
            this.printTestResults();
        } catch (error) {
            console.error('❌ 测试过程中发生错误:', error.message);
            this.addTestResult('整体测试', false, error.message);
        }
    }

    async testHttpLogin() {
        console.log('🔐 步骤1: HTTP登录测试...');
        try {
            await this.registerUser();
            const loginData = await this.makeHttpRequest('/user-service/user/login', 'POST', {
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.passwordHash
            });

            if (loginData.code === 0 && loginData.data) {
                this.userId = loginData.data.userId;
                this.token = loginData.data.accessToken;
                console.log(`✅ 登录成功: userId=${this.userId}`);
                this.addTestResult('HTTP登录', true, `用户ID: ${this.userId}`);
            } else {
                throw new Error(`登录失败: ${loginData.msg || '未知错误'}`);
            }
        } catch (error) {
            console.log('❌ 登录失败:', error.message);
            this.addTestResult('HTTP登录', false, error.message);
            throw error;
        }
    }

    async registerUser() {
        try {
            const res = await this.makeHttpRequest('/user-service/user/register', 'POST', {
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.passwordHash,
                captcha: '123456'
            });
            console.log('📝 用户注册成功', res);
        } catch (error) {
            if (error.message.includes('MOBILE_EXISTS') || error.message.includes('已存在')) {
                console.log('👤 用户已存在，跳过注册');
            } else {
                console.log('⚠️ 注册失败:', error.message);
            }
        }
    }

    async testWebSocketConnection() {
        console.log('\n🔌 步骤2: WebSocket连接测试...');
        return new Promise((resolve, reject) => {
            try {
                const wsUrl = `ws://${CONFIG.server.host}:${CONFIG.server.port}/user-service/websocket?t=${this.token}`;
                this.ws = new WebSocket(wsUrl);

                this.ws.on('open', async () => {
                    console.log('✅ WebSocket连接成功');
                    this.addTestResult('WebSocket连接', true, '连接建立成功');
                    this.setupMessageHandler();
                    await this.delay(500);
                    resolve();
                });

                this.ws.on('error', (error) => {
                    console.log('❌ WebSocket连接失败:', error.message);
                    this.addTestResult('WebSocket连接', false, error.message);
                    reject(error);
                });

                this.ws.on('close', () => {
                    console.log('🔌 WebSocket连接已关闭');
                });

                setTimeout(() => {
                    if (this.ws.readyState === WebSocket.CONNECTING) {
                        this.ws.close();
                        reject(new Error('连接超时'));
                    }
                }, 10000);
            } catch (error) {
                reject(error);
            }
        });
    }

    setupMessageHandler() {
        this.ws.on('message', (data) => {
            try {
                const message = JSON.parse(data.toString());
                console.log('📨 收到消息:', JSON.stringify(message, null, 2));
                this.handleWebSocketResponse(message);
            } catch (error) {
                console.error('❌ 消息解析失败:', error.message);
            }
        });
    }

    handleWebSocketResponse(message) {
        const { act_id, code, roleList, roleCount, data, msg } = message;

        switch (act_id) {
            case 3:
                if (roleList && Array.isArray(roleList)) {
                    this.characters = roleList;
                    console.log(`📋 获取到${roleCount || roleList.length}个角色`);
                }
                break;
            case 4:
                if (code === 0) {
                    console.log('🎯 角色选择成功');
                }
                break;
            case 5:
            case 390:
                if (code === 0) {
                    console.log('🆕 角色创建成功');
                }
                break;
            case 1119:
                if (code === 0 && data && data.list) {
                    this.deputyList = data.list;
                    console.log(`⚔️ 副将列表更新: 共${data.count}个副将`);
                    console.log('📊 副将详情:', JSON.stringify(data.list, null, 2));
                }
                break;
            case 2072:
                this.operationResults.push({
                    act_id: message.act_id,
                    code: message.code,
                    msg: message.msg,
                    data: message.data,
                    timestamp: new Date().toISOString()
                });
                console.log(`⚔️ 副将操作结果:`, JSON.stringify(message, null, 2));
                break;
        }
    }

    async testQueryCharacters() {
        console.log('\n📋 步骤3: 查询角色列表...');
        return new Promise(async (resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                this.addTestResult('查询角色列表', false, 'WebSocket未连接');
                resolve();
                return;
            }

            await this.delay(1000);

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 3) {
                        this.ws.removeListener('message', responseHandler);

                        if (message.roleList && Array.isArray(message.roleList)) {
                            this.characters = message.roleList;
                            console.log(`✅ 查询成功，共${message.roleCount || message.roleList.length}个角色`);
                            this.addTestResult('查询角色列表', true, `获取${this.characters.length}个角色`);
                        } else {
                            this.characters = [];
                            console.log('✅ 查询成功，暂无角色');
                            this.addTestResult('查询角色列表', true, '获取0个角色');
                        }
                        resolve();
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('查询角色列表', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);
            this.ws.send(JSON.stringify({ c: 3, d: null }));

            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                this.addTestResult('查询角色列表', false, '请求超时');
                resolve();
            }, 10000);
        });
    }

    async testCreateCharacter() {
        console.log('\n🆕 步骤4: 创建角色测试...');
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('创建角色', false, 'WebSocket未连接');
            return;
        }

        return new Promise((resolve) => {
            let responseReceived = false;
            let retryCount = 0;
            const maxRetries = 2;

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 5 || message.act_id === 390) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 角色创建成功');
                            this.addTestResult('创建角色', true, '角色创建成功');
                            setTimeout(() => resolve(), 2000);
                        } else {
                            const errorMsg = message.msg || '未知错误';
                            console.log(`❌ 角色创建失败: ${errorMsg}`);

                            if (errorMsg.includes('重复') || errorMsg.includes('已存在') || errorMsg.includes('DUPLICATE')) {
                                if (retryCount < maxRetries) {
                                    retryCount++;
                                    const newName = `${CONFIG.testCharacter.name}_${Date.now()}`;
                                    console.log(`🔄 角色名重复，尝试使用新名字: ${newName}`);
                                    setTimeout(() => {
                                        this.createCharacterWithName(newName, resolve);
                                    }, 1000);
                                    return;
                                }
                            }

                            this.addTestResult('创建角色', false, errorMsg);
                            resolve();
                        }
                    }
                } catch (error) {
                    console.error('❌ 创建角色响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('创建角色', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);
            this.createCharacterWithName(CONFIG.testCharacter.name, resolve);

            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('创建角色', false, '请求超时');
                    resolve();
                }
            }, 15000);
        });
    }

    createCharacterWithName(name, resolve) {
        const createData = {
            c: 5,
            d: {
                name: name,
                sex: CONFIG.testCharacter.sex,
                roleType: CONFIG.testCharacter.roleType,
                headIndex: CONFIG.testCharacter.headIndex
            }
        };

        console.log(`📤 发送创建角色请求:`, JSON.stringify(createData, null, 2));
        this.ws.send(JSON.stringify(createData));
    }

    async testSelectCharacter() {
        console.log('\n🎯 步骤5: 选择角色...');
        if (this.characters.length === 0) {
            console.log('⚠️ 没有可选择的角色');
            this.addTestResult('选择角色', false, '没有可用角色');
            return;
        }

        return new Promise((resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                this.addTestResult('选择角色', false, 'WebSocket未连接');
                resolve();
                return;
            }

            const targetCharacter = this.characters[0];
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 4) {
                        this.ws.removeListener('message', responseHandler);

                        if (message.code === 0) {
                            this.selectedCharacter = targetCharacter;
                            console.log(`✅ 角色选择成功: ${targetCharacter.name} (ID: ${targetCharacter.id})`);
                            this.addTestResult('选择角色', true, `选择角色: ${targetCharacter.name}`);
                            setTimeout(() => resolve(), 2000);
                        } else {
                            console.log(`❌ 角色选择失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('选择角色', false, message.msg || '选择失败');
                            resolve();
                        }
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('选择角色', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);
            this.ws.send(JSON.stringify({
                c: 4,
                d: { characterId: targetCharacter.id }
            }));

            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                this.addTestResult('选择角色', false, '请求超时');
                resolve();
            }, 10000);
        });
    }

    async testQueryDeputyList(tag = '') {
        console.log(`\n⚔️ 步骤6: 查询副将列表(1119) ${tag ? `- ${tag}` : ''}...`);
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('查询副将列表', false, 'WebSocket未连接');
            return;
        }

        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                this.ws.removeListener('message', handler);
                console.log('⚠️ 副将列表查询超时');
                this.addTestResult('查询副将列表', false, '请求超时');
                resolve();
            }, 10000);

            const handler = (raw) => {
                try {
                    const msg = JSON.parse(raw.toString());
                    if (msg && msg.act_id === 1119) {
                        clearTimeout(timeout);
                        this.ws.removeListener('message', handler);
                        if (msg.code === 0) {
                            const data = msg.data || {};
                            this.deputyList = data.list || [];
                            console.log(`✅ 副将列表查询成功: 共${data.count || 0}个副将`);
                            console.log('📊 副将详情:', JSON.stringify(this.deputyList, null, 2));

                            // 验证数据格式
                            if (this.deputyList.length > 0) {
                                const firstDeputy = this.deputyList[0];
                                console.log('🔍 数据格式验证:');
                                console.log(`   - id: ${firstDeputy.id} (${typeof firstDeputy.id})`);
                                console.log(`   - lvl: ${firstDeputy.lvl} (${typeof firstDeputy.lvl})`);
                                console.log(`   - name: ${firstDeputy.name} (${typeof firstDeputy.name})`);
                                console.log(`   - pos: ${firstDeputy.pos} (${typeof firstDeputy.pos})`);
                                console.log(`   - isDeployed: ${firstDeputy.isDeployed} (${typeof firstDeputy.isDeployed})`);
                                console.log(`   - roleType: ${firstDeputy.roleType} (${typeof firstDeputy.roleType})`);
                                console.log(`   - s: ${firstDeputy.s} (${typeof firstDeputy.s})`);
                                console.log(`   - star: ${firstDeputy.star} (${typeof firstDeputy.star})`);
                            }

                            this.addTestResult('查询副将列表', true, `获取${this.deputyList.length}个副将`);
                        } else {
                            console.log('❌ 副将列表查询失败:', msg.msg || msg);
                            this.addTestResult('查询副将列表', false, msg.msg || '查询失败');
                        }
                        return resolve();
                    }
                } catch (_) { }
            };
            this.ws.on('message', handler);
            this.ws.send(JSON.stringify({ c: 1119, d: {} }));
        });
    }

    async testCode2072DeployDeputy() {
        console.log('\n⚔️ 步骤7: 测试2072接口 - 副将上阵(act=4)...');
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('2072接口测试(上阵)', false, 'WebSocket未连接');
            return;
        }

        if (this.deputyList.length === 0) {
            console.log('⚠️ 没有可上阵的副将');
            this.addTestResult('2072接口测试(上阵)', false, '没有可上阵的副将');
            return;
        }

        const deputyToDeploy = this.deputyList[0];
        return new Promise((resolve) => {
            let responseReceived = false;

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 2072) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 副将上阵成功');
                            console.log(`📝 上阵结果: ${message.msg}`);
                            console.log('📊 操作数据:', JSON.stringify(message.data, null, 2));
                            this.addTestResult('2072接口测试(上阵)', true, `副将${deputyToDeploy.id}上阵成功`);
                        } else {
                            console.log(`❌ 副将上阵失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('2072接口测试(上阵)', false, message.msg || '上阵失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    console.error('❌ 副将上阵响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('2072接口测试(上阵)', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);
            this.ws.send(JSON.stringify({
                c: 2072,
                d: { id: deputyToDeploy.id, act: 4 }
            }));

            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('2072接口测试(上阵)', false, '请求超时');
                    resolve();
                }
            }, 10000);
        });
    }

    async testCode2072RemoveDeputy() {
        console.log('\n⚔️ 步骤8: 测试2072接口 - 副将下阵(act=2)...');
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('2072接口测试(下阵)', false, 'WebSocket未连接');
            return;
        }

        // 查找已上阵的副将
        const deployedDeputy = this.deputyList.find(d => d.pos > 0);
        if (!deployedDeputy) {
            console.log('⚠️ 没有已上阵的副将');
            this.addTestResult('2072接口测试(下阵)', false, '没有已上阵的副将');
            return;
        }

        return new Promise((resolve) => {
            let responseReceived = false;

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 2072) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 副将下阵成功');
                            console.log(`📝 下阵结果: ${message.msg}`);
                            console.log('📊 操作数据:', JSON.stringify(message.data, null, 2));
                            this.addTestResult('2072接口测试(下阵)', true, `副将${deployedDeputy.id}下阵成功`);
                        } else {
                            console.log(`❌ 副将下阵失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('2072接口测试(下阵)', false, message.msg || '下阵失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    console.error('❌ 副将下阵响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('2072接口测试(下阵)', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);
            this.ws.send(JSON.stringify({
                c: 2072,
                d: { id: deployedDeputy.id, act: 2 }
            }));

            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('2072接口测试(下阵)', false, '请求超时');
                    resolve();
                }
            }, 10000);
        });
    }

    async testCode2072SwapPosition() {
        console.log('\n⚔️ 步骤9: 测试2072接口 - 副将位置交换(act=3)...');
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('2072接口测试(位置交换)', false, 'WebSocket未连接');
            return;
        }

        // 查找已上阵的副将
        const deployedDeputies = this.deputyList.filter(d => d.pos > 0);
        if (deployedDeputies.length < 2) {
            console.log('⚠️ 上阵副将数量不足，无法进行位置交换');
            this.addTestResult('2072接口测试(位置交换)', false, '上阵副将数量不足');
            return;
        }

        const deputyToSwap = deployedDeputies[0];
        return new Promise((resolve) => {
            let responseReceived = false;

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 2072) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 副将位置交换成功');
                            console.log(`📝 交换结果: ${message.msg}`);
                            console.log('📊 操作数据:', JSON.stringify(message.data, null, 2));
                            this.addTestResult('2072接口测试(位置交换)', true, `副将${deputyToSwap.id}位置交换成功`);
                        } else {
                            console.log(`❌ 副将位置交换失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('2072接口测试(位置交换)', false, message.msg || '位置交换失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    console.error('❌ 副将位置交换响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('2072接口测试(位置交换)', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);
            this.ws.send(JSON.stringify({
                c: 2072,
                d: { id: deputyToSwap.id, act: 3 }
            }));

            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('2072接口测试(位置交换)', false, '请求超时');
                    resolve();
                }
            }, 10000);
        });
    }

    async testCode2072MultipleOperations() {
        console.log('\n⚔️ 步骤10: 测试2072接口 - 多次操作测试...');
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('2072接口测试(多次操作)', false, 'WebSocket未连接');
            return;
        }

        if (this.deputyList.length === 0) {
            console.log('⚠️ 没有可操作的副将');
            this.addTestResult('2072接口测试(多次操作)', false, '没有可操作的副将');
            return;
        }

        // 测试多个副将上阵
        const operations = [
            { deputy: this.deputyList[0], act: 4, name: '上阵副将1' },
            { deputy: this.deputyList[1] || this.deputyList[0], act: 4, name: '上阵副将2' },
            { deputy: this.deputyList[2] || this.deputyList[0], act: 4, name: '上阵副将3' }
        ];

        for (const operation of operations) {
            if (operation.deputy) {
                await this.testSingleOperation(operation.deputy, operation.act, operation.name);
                await this.delay(1000);
            }
        }
    }

    async testSingleOperation(deputy, act, operationName) {
        return new Promise((resolve) => {
            let responseReceived = false;

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 2072) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log(`✅ ${operationName}成功`);
                            this.addTestResult(`2072接口测试(${operationName})`, true, '操作成功');
                        } else {
                            console.log(`❌ ${operationName}失败: ${message.msg || '未知错误'}`);
                            this.addTestResult(`2072接口测试(${operationName})`, false, message.msg || '操作失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult(`2072接口测试(${operationName})`, false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);
            this.ws.send(JSON.stringify({
                c: 2072,
                d: { id: deputy.id, act: act }
            }));

            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult(`2072接口测试(${operationName})`, false, '请求超时');
                    resolve();
                }
            }, 10000);
        });
    }

    async validateOperationResults() {
        console.log('\n🔍 步骤11: 验证副将操作结果...');
        if (!this.operationResults || this.operationResults.length === 0) {
            console.log('⚠️ 没有副将操作结果可供验证');
            this.addTestResult('副将操作结果验证', false, '无操作结果可供验证');
            return;
        }

        const results = this.operationResults;
        let successCount = 0;
        let totalCount = results.length;

        console.log(`📊 开始验证${totalCount}个副将操作结果...`);

        results.forEach((result, index) => {
            if (result.code === 0) {
                successCount++;
                console.log(`✅ 操作${index + 1}成功: ${result.msg}`);
                if (result.data) {
                    console.log(`   操作数据: ${JSON.stringify(result.data)}`);
                }
            } else {
                console.log(`❌ 操作${index + 1}失败: ${result.msg}`);
            }
        });

        console.log(`📊 副将操作结果验证: ${successCount}/${totalCount} 个操作成功`);

        if (successCount > 0) {
            console.log('✅ 副将操作功能测试通过');
            this.addTestResult('副将操作结果验证', true, `${successCount}/${totalCount}个操作成功`);
        } else {
            console.log('❌ 所有副将操作都失败了');
            this.addTestResult('副将操作结果验证', false, '所有操作都失败');
        }
    }

    async testDisconnect() {
        console.log('\n🔌 步骤12: 断开WebSocket连接...');
        if (this.ws) {
            this.ws.close();
        }
        this.addTestResult('断开连接', true, '连接已断开');
    }

    addTestResult(testName, success, message) {
        this.testResults.push({
            test: testName,
            success: success,
            message: message,
            timestamp: new Date().toISOString()
        });
    }

    printTestResults() {
        console.log('\n📊 测试结果汇总:');
        console.log('='.repeat(50));

        let successCount = 0;
        let totalCount = this.testResults.length;

        this.testResults.forEach((result, index) => {
            const status = result.success ? '✅' : '❌';
            console.log(`${index + 1}. ${status} ${result.test}: ${result.message}`);
            if (result.success) successCount++;
        });

        console.log('='.repeat(50));
        console.log(`总计: ${successCount}/${totalCount} 项测试通过`);

        if (successCount === totalCount) {
            console.log('🎉 所有测试通过！2072接口副将操作功能正常！');
        } else {
            console.log('⚠️  部分测试失败，请检查日志');
        }

        if (this.operationResults && this.operationResults.length > 0) {
            console.log('\n⚔️ 副将操作结果分析:');
            console.log('='.repeat(50));
            console.log(`总操作次数: ${this.operationResults.length}`);

            const successOperations = this.operationResults.filter(r => r.code === 0);
            const failedOperations = this.operationResults.filter(r => r.code !== 0);

            console.log(`成功操作: ${successOperations.length}次`);
            console.log(`失败操作: ${failedOperations.length}次`);

            if (successOperations.length > 0) {
                console.log('\n✅ 成功操作详情:');
                successOperations.forEach((op, index) => {
                    console.log(`  ${index + 1}. ${op.msg} (${op.timestamp})`);
                    if (op.data) {
                        console.log(`     数据: ${JSON.stringify(op.data)}`);
                    }
                });
            }

            if (failedOperations.length > 0) {
                console.log('\n❌ 失败操作详情:');
                failedOperations.forEach((op, index) => {
                    console.log(`  ${index + 1}. ${op.msg} (${op.timestamp})`);
                });
            }
        }

        if (this.deputyList && this.deputyList.length > 0) {
            console.log('\n⚔️ 最终副将状态:');
            console.log('='.repeat(50));
            this.deputyList.forEach((deputy, index) => {
                const status = deputy.pos > 0 ? `上阵(位置${deputy.pos})` : '下阵';
                const deployedStatus = deputy.isDeployed ? '已上阵' : '未上阵';
                console.log(`  ${index + 1}. ID: ${deputy.id}, 名称: ${deputy.name}, 状态: ${status}, 上阵状态: ${deployedStatus}, 星级: ${deputy.s}`);
            });
        }
    }

    async makeHttpRequest(path, method = 'GET', data = null) {
        return new Promise((resolve, reject) => {
            const options = {
                hostname: CONFIG.server.host,
                port: CONFIG.server.port,
                path: path,
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                }
            };

            if (data) {
                const postData = JSON.stringify(data);
                options.headers['Content-Length'] = Buffer.byteLength(postData);
            }

            const req = http.request(options, res => {
                let body = '';
                res.on('data', (chunk) => { body += chunk; });
                res.on('end', () => {
                    try {
                        const responseData = JSON.parse(body);
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(responseData);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${responseData.message || body}`));
                        }
                    } catch (error) {
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(body);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${body}`));
                        }
                    }
                });
            });

            req.on('error', (error) => { reject(error); });
            if (data) { req.write(JSON.stringify(data)); }
            req.end();
        });
    }

    async delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

async function main() {
    const tester = new Code2072Tester();
    await tester.runTest();
}

if (require.main === module) {
    main().catch((error) => {
        console.error('💥 测试脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = Code2072Tester;
